<?php

namespace app\helper;

use app\helper\CommonHelper;
use app\model\User;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;

class JwtHelper
{
    /**
     * 定义JWT key
     */
    private $key = "ReseedPuppyVeryGood";

    /**
     * 定义JWT 中payload
     */
    private $payload = [];

    public function __construct()
    {
        $this->key = User::find(1) ? User::find(1)['password'] : CommonHelper::get_rand_str();
    }

    public function encode($payload)
    {
        $jwt = JWT::encode($payload, $this->key, 'HS256');
        return $jwt;
    }
    public function decode($jwt)
    {
        try {
            $decoded = JWT::decode($jwt, new Key($this->key, 'HS256'));
        } catch (\Exception $e) {
            $decoded = 0;
        }
        return $decoded;
    }
}
